package com.yuhf.dbutils;

import com.yuhf.dbutils.exception.AccessDbException;
import lombok.extern.log4j.Log4j;

import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 获取数据库连接类
 */
@Log4j
public class DBConnection {

    private static ThreadLocal<Connection> threadLocal = new ThreadLocal<>();

    private static final String DRIVER_CLASS_NAME;
    private static final String URL;
    private static final String USERNAME;
    private static final String PASSWORD;

    static {
        Properties prop = new Properties();
        try {
            prop.load(DBConnection.class.getResourceAsStream("/jdbc.properties"));
        } catch (IOException e) {
            log.error("jdbc.properties file not found,message is" + e.getMessage());
        }
        DRIVER_CLASS_NAME = prop.getProperty("jdbc.driverClassName");
        URL = prop.getProperty("jdbc.url");
        USERNAME = prop.getProperty("jdbc.userName");
        PASSWORD = prop.getProperty("jdbc.password");
        try {
            Class.forName(DRIVER_CLASS_NAME);
        } catch (ClassNotFoundException e) {
            log.error("class not found,message is " + e.getMessage());
            throw new AccessDbException("数据库驱动类没有找到");
        }
    }

    public static Connection getConnection() {
        Connection connection = threadLocal.get();
        try {
            if (null == connection || connection.isClosed()) {
                connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
            }
            threadLocal.set(connection);
        } catch (SQLException e) {
            log.error("create connection error,message is " + e.getMessage());
            throw new AccessDbException("数据库连接创建失败");
        }
        return connection;
    }

    public static void closeConnection(Connection connection) {
        try {
            if (null != connection && connection.getAutoCommit()) {
                connection.close();
            }
        } catch (SQLException e) {
            log.error("close connection error,message is " + e.getMessage());
            throw new AccessDbException("数据库连接关闭失败");
        }
    }
}
